var _x = (function () {

    var global_id = 0;
    var getid = function () {
        return global_id++;
    };

    var _x = function (tagname, prop) {
        this.e = document.createElement(tagname);
        this.prop = prop;
        this.child = {};
        this.parent = null;
        this._id = getid();
        _x.docs[this._id] = this;
        var self = this;
        for (var i in prop) {
            if (i == "css") {
                for (var css in prop["css"]) {
                    var cssval = prop.css[css];
                    this.e.style[css] = cssval;
                }
            } else if (i == "class") {
                this.e.className = prop.class;
            } else if (i == "event") {
                for (var event in prop.event) {
                    var eventfunc = function (e) {
                        var ef = self.prop.event[event];
                        ef(e, self);
                    }.bind(self);
                    this.e.addEventListener(event, eventfunc);
                }
            } else if (i == "html") {
                this.e.innerHTML = prop.html;
            } else if (i == "child") {
                var childs = prop.child;
                var chs = _x.create(childs);
                for (var c in chs) {
                    this.add(chs[c]);
                }
            } else {
                this.e.setAttribute(i, prop[i]);
            }
        }
    };
    _x.prototype.add = function (x) {
        for (var i in arguments) {
            var arg = arguments[i];
            arg.parent = this;
            this.child[arg._id] = arg;            
            this.e.appendChild(arg.e);
        }
    };
    _x.prototype.remove = function (x) {
        if (arguments.length == 0) {
            _x.remove(this._id);
        } else {
            for (var i = 0; i < arguments.length; i++) {
                var obj = arguments[i];
                _x.remove(obj._id);               
            }
        }
    };
    _x.prototype.val = function () {
        return this.e.value;
    };
    _x.docs = {};
    _x.remove = function (id) {
        _x.docs[id].e.remove();
        delete _x.docs[id];
    };
    
    _x.create = function (objs) {
        var docs = [];
        for (var i = 0; i < objs.length; i++) {
            var obj = objs[i];
            for (var tag in obj) {
                var x = new _x(tag, obj[tag]);
                docs.push(x);
            }
        }
        return docs;
    };
    return _x;
})();